<?php
/**
 * 智能名片
 */

namespace app\api\model;

use custom\Err;
use oss\Oss;
use PDOStatement;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;
use think\Exception;
use app\api\controller\Config;
use app\common\lib\RespCode;

class Agent extends Model {

    /**
     * 名片个人信息
     */
    public function getAgent($params,$info) {
        $field="a.id,a.phone,a.name,a.wechat,a.position,a.template_id,a.wechat_code,a.cover,b.name company_name,b.province,b.city,b.area,b.address";

        $data = db('company_agent')
            ->alias('a')
            ->field($field)
            ->join('erp_company b','a.company_id=b.id','left')
            ->where("a.id={$params['agent_id']} and a.company_id={$info['company_id']}")
            ->find ();
        $data['name']=base64_decode($data['name']);
        return $data;
    }

    /**
     * 高校列表
     */
    public function getSchool($params,$pagesize) {
        $where="1=1";
        if ($params['name']){
            $where .=" and name like '%{$params['name']}%'";
        }
        $data=db('school')->field('id,name')->where($where)->page($params['page'],$pagesize)->select();
        return $data;
    }

    /**
     * 城市列表
     * @return mixed
     */
    public function getAddre() {
        $re=db('region')->field('id,name,city_code,pid')->where('rank in(1,2)')->order('rank asc')->select();
       $add_array=array(
           ['id'=>-1,'name'=>'澳门','city_code'=>820000,'pid'=>25179],
           ['id'=>-2,'name'=>'香港','city_code'=>810000,'pid'=>25183]
           );
       $re=array_merge($re,$add_array);
//       halt($re);
        //处理数据结构
        $data=$this->generateTree($re);
        return $data;
    }

    //转为指定树状结构
    public function generateTree($data)
    {
        $items = array();
        foreach ($data as $v) {
            $items[$v['id']] = $v;
        }
        $tree = array();
        foreach ($items as $k => $item) {
            if (isset($items[$item['pid']])) {
                $items[$item['pid']]['son'][] = &$items[$k];
            } else {
                $tree[] = &$items[$k];
            }
        }
        return $tree;
    }

    /**
     * 标签
     * @return mixed
     */
    public function getTag() {
        $data=db('label')->field('name')->select();
        return $data;
    }

    /**
     * 名片推荐房源
     * @param $params
     * @param $pagesize
     */
    public function getRecommendHouse($params,$pageSize){
        $where="a.agent_id={$params['agent_id']} and h.is_shelf=1 and h.deleted=0";
        $field=['a.name house_name,a.desc house_desc,a.id recommend_id,a.is_modify'];
        $House = new House();
        $column = array_merge($House->houseFields, $House->villageFields, $House->typeFields, $House->auctionFields,$House->businessFields,$House->reginFields,$field);

        $data=db('recommend_house')
            ->alias('a')
            ->field($column)
            ->join('erp_company_agent b','a.agent_id=b.id','left')
            ->join('erp_house h','a.house_id=h.id','left')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->where($where)
            ->order('ha.auction_status asc,a.utime desc')
            ->page($params['page'], $pageSize)
            ->select();
        $count=db('recommend_house')
            ->alias('a')
            ->join('erp_company_agent b','a.agent_id=b.id','left')
            ->join('erp_house h','a.house_id=h.id','left')
            ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->join('erp_house_type ht', 'h.house_type_id = ht.id', 'LEFT')
            ->join('erp_house_village hv', 'h.village_id = hv.id', 'LEFT')
            ->join('erp_business_area hb', 'h.business_area_id = hb.id', 'LEFT')
            ->join('erp_region hr', 'h.city_code = hr.city_code', 'LEFT')
            ->where($where)
            ->count();

        $data=House::house_list_style($data);
        $data=$this->recommendHouseStyle($data);
        $list['count']=$count;//数据总条数
        $list['page']=$params['page'];//当前页码
        $list['pageSize']=$pageSize;//每页显示条数
        $list['pageNum']=ceil($list['count']/$pageSize);//每页显示条数
        $list['list']=$data?$data:[];//每页显示条数
        return $list;

    }

    /**
     * 经纪人推荐房源数据
     * @param $data
     * @return string
     */
    public function recommendHouseStyle($data=[]){

        if (!$data){
            return [];
        }
        foreach ($data as $key =>$value){
            if ($value['is_modify']==0&&($value['house_name']!=$value['title'])){
                $data[$key]['house_name']=$value['title'];
                $this->updateRecommendName($value['recommend_id'],$value['title']);
            }
            unset($data[$key]['is_modify']);
        }
        return array_values($data);
    }


    /**
     * 名片页信息
     * @param $params
     * @return mixed
     */
    public function getCardInfo($params){

        //经纪人信息
        $field = "a.id agent_id,a.phone,a.name,a.cover,a.wechat_code,a.position,a.template_id,a.province,a.city,a.city_codes,a.education,a.voice,a.voice_time,a.describe,a.label,a.pics,a.company_shop_id,a.address company_address";
        $field .= ",b.video,b.video_cover,b.name company_name,b.province company_province,b.city company_city,b.area company_area";
        $res = db('company_agent')
            ->alias('a')
            ->field($field)
            ->join('erp_company b','a.company_id=b.id','left')
            ->where("a.id={$params['agent_id']} and a.company_id={$params['company_id']}")
            ->find ();
        //名片信息
        $card['agent_id']=$res['agent_id'];//电话
        $card['phone']=$res['phone'];//电话
        $card['name']=$res['name'];//名称
        $card['position']=$res['position'];//职位
        $card['template_id']=$res['template_id'];//名片模板id（1：大气版，2：商务版，3：黑金版，4：仰望版，5：简约版）
        $card['wechat_code']=$res['wechat_code'];//小程序二维码
        $card['cover']=$res['cover']?$res['cover']:config('global.default_avt');//头像
        $card['company_name']=$res['company_name'];//公司名称
        $card['company_province']=$res['company_province'];//公司省份
        $card['company_city']=$res['company_city'];//公司城市
        $card['company_area']=$res['company_area'];//公司区县
        $card['company_address']=$res['company_address'];//公司详细地址
        if ($res['company_shop_id']){
            $shop=db('company_shop')->where("id={$res['company_shop_id']}")->find();
            $company_shop_name=$shop['name'];
            $card['company_province']=$shop['province'];//门店省份
            $card['company_city']=$shop['city'];//门店城市
            $card['company_area']=$shop['area'];//门店区县
        }else{
            $company_shop_name='';
        }
        $card['company_shop_name']=$company_shop_name;//门店名称
        $data['card']=$card?$card:[];
        //个人简介
        $agent['province']=$res['province'];//我的家乡（省份）
        $agent['city']=$res['city'];//我的家乡（城市）
        $agent['education_id']=$res['education']?$res['education']:0;//学历（1高中、2大专、3本科、4硕士、5博士、6其它）
        switch ($res['education']){
            case 1;
                 $agent['education_name']='高中';
            break;
            case 2;
                 $agent['education_name']='大专';
            break;
            case 3;
                 $agent['education_name']='本科';
            break;
            case 4;
                 $agent['education_name']='硕士';
            break;
            case 5;
                 $agent['education_name']='博士';
            break;
            case 6;
                 $agent['education_name']='其他';
            break;
            default:
                $agent['education_name']='';
        }
        $agent['city_codes']=$res['city_codes'];//城市code集合,例：1,11,22,
        $c_code=$res['city_codes']?explode(',',$res['city_codes']):'';
        $agent['city_codes']=$c_code?$c_code[1]:'';
        $agent['voice']=$res['voice'];//录音地址
        $agent['voice_time']=$res['voice_time'];//录音时长
        $agent['describe']=$res['describe']?base64_decode($res['describe']):'';//自我描述
        $agent['label']=$res['label']?explode(',',$res['label']):[];//标签（逗号隔开，最多四个标签）
        $data['agent']=$agent?$agent:[];
        //推荐房源
        $data['recommend_house']=$this->recommend($res['agent_id']);
        //我的视频
        $video['video_url']=$res['video']?$res['video']:'';//视频地址
        $video['video_cover']=$res['video_cover']?$res['video_cover']:'';//视频封面图
        $data['video']=$video?$video:[];
        //我的照片
        $data['photo']=$res['pics']?explode(',',$res['pics']):[];//最多9张”,”逗号隔开
        return $data;
    }


    /**
     * 教育经历详情
     * @param $params
     * @return mixed
     */
    public function getEducationInfo($params){
        $field="school_name,school_id,education education_id,major,school_s_time,school_e_time";
        $data=db('company_agent')->field($field)->where("id={$params['agent_id']}")->find();
        $data['education_id']=$data['education_id']?$data['education_id']:0;
        switch ($data['education_id']){
            case 1;
                $data['education_name']='高中';
                break;
            case 2;
                $data['education_name']='大专';
                break;
            case 3;
                $data['education_name']='本科';
                break;
            case 4;
                $data['education_name']='硕士';
                break;
            case 5;
                $data['education_name']='博士';
                break;
            case 6;
                $data['education_name']='其他';
                break;
            default:
                $data['education_name']='';
        }
        return $data;
    }
    /**
     * 名片展示推荐房源
     * @param int $agent_id
     * @return mixed
     */
    public function recommend($agent_id=0){
        $where="a.agent_id={$agent_id} and c.is_shelf=1 and c.deleted=0";
        $field="a.name,a.desc,a.is_modify,a.id recommend_id,c.cover,d.initial_price,d.end_time,c.title,c.bedroom,c.livingroom,e.name hv_name,c.id house_id";
        $data=db('recommend_house')
            ->alias('a')
            ->field($field)
            ->join('erp_company_agent b','a.agent_id=b.id','left')
            ->join('erp_house c','a.house_id=c.id','left')
            ->join('erp_house_auction d','c.auction_id=d.id','left')
            ->join('erp_house_village e','c.village_id=e.id','left')
            ->where($where)
            ->order('d.auction_status asc,a.utime desc')
            ->limit(0,2)
            ->select();
        foreach ($data as $key =>$value){
            $hv_name=$data[$key]['hv_name']??'';
            if ($data[$key]['bedroom']&&$data[$key]['livingroom']){
                $boor=$value['bedroom'].'室'.$value['livingroom'].'厅';
            }else{
                $boor='';
            }
            $title=$hv_name?$hv_name.' '.$boor:$value['title'];
            $data[$key]['title']=$title;
            if ($value['is_modify']==0&&($value['name']!=$title)){
                $data[$key]['name']=$title;
                $this->updateRecommendName($value['recommend_id'],$title);//更新推荐名称
            }
            unset($data[$key]['bedroom']);
            unset($data[$key]['livingroom']);
            unset($data[$key]['hv_name']);
            unset($data[$key]['is_modify']);
            $data[$key]['cover']=$value['cover'] ? $value['cover'] : config('global.empty_house_img');//封面图
            $data[$key]['end_time']=$value['end_time'] ? date('Y-m-d H:i',$value['end_time']) : '';//结束时间
            deal_money_list ($value['initial_price'], $initial_price, $initial_price_unit);//初始价格
            $data[$key]['initial_price'] = $initial_price;
            $data[$key]['initial_price_unit'] = $initial_price_unit;
        }
        return $data;
    }

    /**
     * 名片模板样式保存
     * @param $params
     * @return int|string
     */
    public function templateSave($params,$info) {
        $update['cover']=isset($params['cover'])?$params['cover']:'';//名片头像
        $per='/^(https:\/\/oss.fpaiyun.com|http:\/\/oss.fpaiyun.com).{1,}$/';
        //判断图片路径是否正确
        if (!preg_match($per,$update['cover'])){
            Err::add('头像路径错误',RespCode::PARAMS_ERR);
            return false;
        }
        //判断图片是否存在
        if (!img_exists($update['cover'])){
            Err::add('头像不存在',RespCode::PARAMS_ERR);
            return false;
        }

        $def_cover= config('global.default_avt');
        $del_cover='';
        $del_temp_cover='';
        if ($info['cover']&&($info['cover']!=$update['cover'])&&($info['cover']!=$def_cover)){
            //删除原有的头像
          $del_cover=$info['cover'];
        }

        $update['template_id']=$params['template_id'];//名片模板id
        $update['template_cover']=$params['template_cover']??'';//名片模板id
        if ($info['template_cover']&&($info['template_cover']!=$update['template_cover'])){
            //名片模板图片
            $del_temp_cover=$info['template_cover'];
        }
        $update['utime']=time();
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if($res!==false){
            $oss=Oss::getInstance();
            if ($del_cover){
                $oss->delOneFile($del_cover);

            }
            if ($del_temp_cover){
                $oss->delOneFile($del_temp_cover);

            }
            return true;
        }else{
            return false;
        }
    }

    /**
     * 名片个人信息保存
     * @param $params
     * @return int|string
     */
    public function agentSave($params){
        $update['position']=$params['position'];//职位
        $update['wechat']=$params['wechat'];//微信号
        $update['utime']=time();
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            return false;
        }

    }

    /**
     * 家乡信息保存
     * @param $params
     * @return int|string
     */
    public function homeSave($params){
        if (($params['city_code']==810000)||($params['city_code']==820000)){
            $update['province']=($params['city_code']==810000)?'香港':'澳门';//省份
            $update['city']=($params['city_code']==810000)?'香港':'澳门';//城市
            $update['city_codes']=$params['city_code'].','.$params['city_code'];//城市code集合，例：1,11,22
        }else{
            $re= db('region')
                ->alias('a')
                ->field('a.city_code c_code,b.city_code p_code,a.name c_name,b.name p_name')
                ->join('erp_region b','a.pid=b.id','left')
                ->where("a.city_code={$params['city_code']}")
                ->find();
            $update['province']=$re['p_name'];//省份
            $update['city']=$re['c_name'];//城市
            $update['city_codes']=$re['p_code'].','.$re['c_code'];//城市code集合，例：1,11,22
        }



        $update['utime']=time();
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 教育经历信息保存
     * @param $params
     * @return int|string
     */
    public function educationSave($params){
        $update['school_name']=isset($params['school_name'])?$params['school_name']:'';//学校名称
        $update['school_id']=isset($params['school_id'])?$params['school_id']:'';//学校关联id
        $update['education']=isset($params['education_id'])?$params['education_id']:'';//学历：1高中、2大专、3本科、4硕士、5博士、6其它
        $update['major']=isset($params['major'])?trim($params['major']):'';//专业
        if (mb_strlen($update['major'])>10){
            Err::add('专业填写格式错误',RespCode::PARAMS_ERR);
            return false;

        }
        $update['school_s_time']=isset($params['school_s_time'])?$params['school_s_time']:0;//在校开始时间（例：2016）
        $update['school_e_time']=isset($params['school_e_time'])?$params['school_e_time']:0;//在校结束时间（例：2020）
        $update['utime']=time();
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            Err::add('保存失败',RespCode::PARAMS_ERR);
            return false;
        }
    }

    /**
     *  保存自我描述
     * @param $params
     * @return int|string
     */
    public function describeSave($params){
        $str=isset($params['describe'])?trim($params['describe']):'';
        if (mb_strlen($str)>100){
            Err::add('自我描述填写格式错误',RespCode::PARAMS_ERR);
            return false;
        }
        $update['describe']=isset($params['describe'])?base64_encode($str):'';//自我描述
        $update['utime']=time();//操作时间
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            Err::add('保存失败',RespCode::QUERY_ERR);
            return false;
        }
    }

    /**
     * 标签保存
     * @param $params
     * @return int|string
     */
    public function tagSave($params){
        $labbel=isset($params['label'])?trim($params['label']):'';//标签

        if ($labbel){
            $str='';
            $arr=explode(',',$labbel);
            foreach ($arr as $value){
                $item=rtrim($value);
                if (mb_strlen($item)>7){
                    Err::add('标签填写格式错误',RespCode::PARAMS_ERR);
                    return false;
                }else{
                    $str.=$item.',';
                }

            }

            $labbel= substr($str,0,strlen($str)-1);
        }
        $update['label']=$labbel;
        $update['utime']=time();//操作时间
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            Err::add('保存失败',RespCode::PARAMS_ERR);
            return false;
        }
    }

    /**
     * 录音保存
     * @param $params
     * @return int|string
     */
    public function voiceSave($params){
        $update['voice']=$params['voice'];//录音地址
        $update['voice_time']=$params['voice_time'];//录音时长
        $update['utime']=time();//操作时间
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 推荐房源编辑
     * @param $params
     * @return int|string
     */
    public function recommendHouseModify($params){

        $update['name']=isset($params['name'])?trim($params['name']):'';//房源名称标题
        $update['desc']=isset($params['desc'])?trim($params['desc']):'';//房源描述
        $update['is_modify']=1;//房源标题是否被编辑， 1已编辑 0未编辑
        if (!$update['name']){
            $house_id=db('recommend_house')->where("id={$params['id']}")->value('house_id');
            $house=db('house')
                ->alias('h')
                ->field('h.title,h.bedroom,h.livingroom,hv.name hv_name')
                ->join('erp_house_village hv','h.village_id=hv.id','left')
                ->where("h.id={$house_id}")
                ->find();
            $hv_name=$house['hv_name']??'';
            if ($house['bedroom']&&$house['livingroom']){
                $boor=$house['bedroom'].'室'.$house['livingroom'].'厅';
            }else{
                $boor='';
            }
            $title=$hv_name?$hv_name.' '.$boor:$house['title'];
            $update['name']=$title;
            $update['is_modify']=0;//房源标题是否被编辑， 1已编辑 0未编辑
        }
        if (mb_strlen($update['name'])>40){
            Err::add("房源标题填写格式错误",RespCode::PARAMS_ERR);
            return false;
        }

        if (mb_strlen($update['desc'])>100){
            Err::add("房源描述填写格式错误",RespCode::PARAMS_ERR);
            return false;
        }
        $update['utime']=time();//更新时间
        $res=db('recommend_house')->where("id={$params['id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            Err::add("保存失败",RespCode::QUERY_ERR );
            return false;
        }

    }

    /**
     * 我的照片保存
     * @param $params
     * @return int|string
     */
    public function picsSave($params){
        $update['pics']=isset($params['pics'])?$params['pics']:'';//图片地址
        $update['utime']=time();//操作时间
        $res=db('company_agent')->where("id={$params['agent_id']}")->update($update);
        if ($res!==false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 经纪人个人信息
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getpersonal($params) {
        $data = db('company_agent')
            ->alias('a')
            ->field('a.id,a.name,a.phone,a.position,a.cover,a.is_push,a.company_shop_id,a.address,b.name company_name,b.province,b.city,b.area,c.name company_shop_name,c.province shop_province,c.city shop_city,c.area shop_area')
            ->join('erp_company b','a.company_id=b.id','left')
            ->join('erp_company_shop c','a.company_shop_id=c.id','left')
            ->where("a.id={$params['agent_id']}")
            ->find();

        if (empty($data['phone'])) {
            $phone = '';
        } else {
            $phone = $data['phone'];
        }
        $main_id = md5(md5($params['agent_id']));

        if (empty(AgentDemand::getMycount($params['agent_id']))) {
            $is_demand = 0;
        } else {
            $is_demand = 1;
        }

        return ['avatar' => empty($data['cover']) ? config('global.default_avt') : $data['cover'],
            'nickname' => $data['name'],
            'phone' => $phone,
            'id' => $main_id,
            'is_demand' => $is_demand,
            'is_push' => $data['is_push'],
            'position'=>$data['position'],
            'company_name'=>$data['company_name'],
            'company_shop_name'=>$data['company_shop_name']?$data['company_shop_name']:'',
            'province'=>$data['company_shop_id']?$data['shop_province']:$data['province'],
            'city'=>$data['company_shop_id']?$data['shop_city']:$data['city'],
            'area'=>$data['company_shop_id']?$data['shop_area']:$data['area'],
            'address'=>$data['address']
        ];
    }

    /**
     * 经纪人修改头像
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public function editAvatar($params,$info) {
        $params['avatar']=$params['avatar']?$params['avatar']:'';
        $per='/^(https:\/\/oss.fpaiyun.com|http:\/\/oss.fpaiyun.com).{1,}$/';
        //判断图片路径是否正确
        if (!preg_match($per,$params['avatar'])){
            Err::add('头像路径错误',RespCode::PARAMS_ERR);
            return false;
        }
        //判断图片是否存在
        if (!img_exists($params['avatar'])){
            Err::add('头像不存在',RespCode::PARAMS_ERR);
            return false;
        }
        $data = [
            'cover' => $params['avatar']
        ];

        $re=db('company_agent')->where('id', $params['agent_id'])->update($data);
        if ($re===false){
            Err::add('操作失败',RespCode::QUERY_ERR);
           return false;
        }else{
           return true;
        }
    }

    /**
     * 添加反馈
     * @param $params
     * @return int|string
     */
    public function addProblem($params) {
        if (mb_strlen($params['content'], "utf-8") > 100) {
            throw new Exception('内容不能超过100个字符', RespCode::QUERY_ERR);
        }
        $data = [
            'agent_id' => $params['agent_id'],
            'content' => $params['content'],
            'pic' => empty($params['pic']) ? '' : $params['pic'],
            'itime' => time()
        ];
        return db("company_agent_problem")->insert($data);
    }

    /**
     * 修改推送状态
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function editPushStatus($params) {
        if (empty($params['type'])) {
            $type = 0;
        } else {
            $type = 1;
        }
        return db('company_agent')->where('id', $params['agent_id'])->update(['is_push' => $type]);
    }

    /**
     * 查询用户是否是关联经纪人的 专属客户
     * @param int $agent_id
     * @param int $user_id
     * @return bool
     */
    public function getAgentUser($agent_id=0,$user_id=0){
        $re=db('company_agent_user')->where("user_id={$user_id} and agent_id={$agent_id}")->find();
        if ($re){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更新推荐房源名称
     * @param $id
     * @param $name
     */
    public function updateRecommendName($id,$name){
        db('recommend_house')->where('id',$id)->update(['name'=>$name]);
    }

}
